<template>
  <div>
    <div class="subjectBox flex flex-row">
      <div class="fl2">
        <div v-for="item in subjectListCopy" class="subjectRow flex flex-row">
          <div class="check flex a-item j-content"><el-checkbox v-model="item.checked" @change="changeCheck(item)"></el-checkbox></div>
          <div class="subjectName  flex a-item fl1">{{ item.name }}</div>
          <div class="fl1">
            <el-select v-model="item.algorithm" placeholder="请选择">
              <el-option
                v-for="item in algorithmType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="fl1 computed">
        {{ getCheckSubject }}
      </div>
    </div>
    <div class="bottom flex flex-reverse"><el-button type="success" @click="removeFormula">清空</el-button><el-button type="success" @click="submitFormula">确定</el-button></div>
  </div>
</template>

<script>
export default {
  name: 'setFormula',
  props:{
    subjectList:{
      type:Array,
      default:[]
    },
    obj:Object
  },
  created() {
    this.setCheck()
  },
  data(){
    return{
      algorithmType:[
        {label:'加',value:1},
        {label:'减',value:0}
      ],
      subjectListCopy:{}
    }
  },
  methods:{
    submitFormula(){
      const formula = this.subjectListCopy.filter(item=>item.checked).map(item=>{
        return{
          id:item.id,
          name: item.name,
          type:item.algorithm
        }
      })
      this.obj.formula = formula
      this.$emit('close',true)
    },
    removeFormula(){
      this.$set(this.obj,'formula',[])
      this.subjectListCopy.filter(item=>item.checked).forEach(item=>{
        item.checked = false
        this.$set(item,'algorithm',null)
      })
    },
    setCheck(){
      this.subjectListCopy = JSON.parse(JSON.stringify(this.subjectList))
      if (!this.obj.formula) return
      this.obj.formula.forEach(item=>{
        const subject = this.subjectListCopy.find(val=>item.id === val.id)
        this.$set(subject,'checked',true)
        this.$set(subject,'algorithm',item.type)
      })
    },
    changeCheck(e){
      if(e.algorithm === undefined || e.algorithm === null)
        this.$set(e,'algorithm',1)
    }
  },
  computed:{
    getCheckSubject(){
      let str = ''
      this.subjectListCopy.filter(item=>item.checked).forEach(item=>
        str += `${item.algorithm?'+':'-'} ${item.name} `
      )
      if(/^\+/.test(str))str = str.substr(1)
      return  this.obj.name + '= '+str
    }
  }
}
</script>

<style lang="scss" scoped>
.subjectBox{
  height: 500px;
  overflow: auto;
  .subjectRow{
    height: 30px;
    .check{
      width: 30px;
      height: 30px;
      border: 1px solid #000000 ;
    }
    .subjectName{
      padding-left: 10px;
      font-size: 20px;
      border: 1px solid  #000000 ;
    }
  }
}
.computed{
  font-size: 18px;
}
</style>
